import React, { useState, useMemo, useEffect } from "react";
import { NavBar, Empty, Space, Toast, Steps } from "antd-mobile";
import { getSearchParams } from "src/utils/index";
import {
    findCustomInfo,
    findHistoryProcess,
    findCurrentProcess,
    findPreviewProcess,
    chk,
} from "src/api/pqsstartWkInfo";
import "./index.scss";
import { locationShape, historyShape, storeShape } from "src/propType";

const { Step } = Steps;

const status = {
    AGREE: "已同意",
    AUTOAGREE: "已自动同意",
    AUTOREJECT: "已自动拒绝",
    CANCEL: "已撤回",
    REVIEWED: "待审核",
    INPROCESS: "审核中",
    AUDITED: "已审核",
    NULL: "未进行操作",
    BACKOUT: "已撤回",
    REJECT: "已拒绝",
    SEND: "已抄送",
    NOTDONE: "流程未进行",
};

const colors = {
    REVIEWED: "#EE9E00", // 待审核
    INPROCESS: "#F4AC16", // 审核中
    AUDITED: "#1FCDB6", // 已审核
    NULL: "#4999FC", // 未进行操作
    REJECT: "#f56c6c", // 已拒绝
    SEND: "#67c23a", // 已抄送
    AUTOREJECT: "#f56c6c", // 已自动拒绝
    CANCEL: "#f56c6c", // 已撤销
    BACKOUT: "#FF6666", // 撤回
    SENDBACK: "#6B73B9", // 退回
    AUTOAGREE: "#67c23a", // 已自动同意
    AGREE: "#67c23a", // 已同意
    NOTDONE: "#CED0DA", // 流程未进行
    DEFAULT: "#4999FC",
};

const showSignFile = false;

const StatusFlow = props => {
    const [_stepInfo, set_stepInfo] = useState({
        activeNode: 100,
        nodeList: [],
    });

    const { store, history, location } = props;
    const userData = store.user.userData;

    // 工作流数据

    const lastParams = useMemo(() => {
        const params = getSearchParams(location.search);
        return params;
    }, [location.search]);

    const getWorkflowKid = () => {
        const kid = lastParams.kid;
        if (!kid) return;
        findCustomInfo(kid).then(res => {
            if (res.success) {
                getCurrentNodeId(kid).then(result => {
                    getWorkflowNode(res.data[0].processDefinitionKey, result);
                });
            }
        });
    };

    const getCurrentNodeId = kid => {
        return new Promise(resolve => {
            findCurrentProcess(kid).then(res => {
                if (res.success) {
                    let nodelist = res.data[0].nodeList.map((ee, idx) => ({
                        nodeIndex: idx,
                        nodeId: ee.nodeId,
                        nodeName: ee.nodeName,
                        procInstStatus: "INPROCESS",
                        assigneeList: ee.assigneeList,
                    }));
                    resolve(nodelist);
                }
            });
        });
    };

    // 获取当前之后的流程
    const getWorkflowNode = (key, curr) => {
        let resprev = [],
            resAfter = [];
        let addUserId = lastParams.addUserId;
        //提交数据的kid
        let businesskey = lastParams.kid;
        findPreviewProcess(
            addUserId || userData.userId, // 提交审核人Id
            key, // 前一个步骤的 processDefinitionKey
            curr[curr.length - 1].nodeId, // 最后一个步骤的nodeId
            businesskey,
        )
            .then(res => {
                if (res.success) {
                    resAfter = res.data;
                    findHistoryProcess(lastParams.kid).then(res => {
                        // 当前节点之前的流程节点
                        let nodeList = [],
                            activeNode = 1;
                        let prevArr = res.data
                            .map(item => ({
                                procInstStatus: item.procInstStatus,
                                nodeList: item.nodeList,
                            }))
                            .reverse();
                        for (let i = 0; i < prevArr.length; i++) {
                            const ele1 = prevArr[i];
                            if (ele1.nodeList?.length) {
                                for (let j = 0; j < ele1.nodeList.length; j++) {
                                    const ele2 = ele1.nodeList[j];
                                    resprev.push({
                                        nodeId: ele2.nodeId,
                                        nodeName: ele2.nodeName,
                                        assigneeList: ele2.assigneeList,
                                        procInstStatus: ele1.procInstStatus,
                                    });
                                }
                            }
                        }

                        let next = resAfter.map((e, idx) => ({
                            nodeId: e.nodeId,
                            nodeName: e.nodeName,
                            assigneeList: e.assigneeList,
                            procInstStatus: "NOTDONE", // 流程未进行
                        }));

                        let arrlist = resprev.concat(next);

                        for (let z = 0; z < arrlist.length; z++) {
                            const ele11 = arrlist[z];
                            if (ele11.assigneeList) {
                                for (let d = 0; d < ele11.assigneeList.length; d++) {
                                    const ele22 = ele11.assigneeList[d];
                                    ele22.fileData = [];
                                    if (ele22.taskId && showSignFile) {
                                        // getUploadData(ele22.taskId).then(result => {
                                        //     ele22.fileData = result;
                                        // });
                                    }
                                }
                            }
                        }

                        if (arrlist.length > 0) {
                            nodeList = [{ nodeId: "0", nodeName: "流程开始", assigneeList: [] }];
                        }

                        nodeList = nodeList.concat(arrlist);

                        if (arrlist.length > 0) {
                            nodeList.push({
                                nodeId: "100",
                                nodeName: "流程结束",
                                assigneeList: [],
                            });
                        }

                        for (let i = 0; i < nodeList.length; i++) {
                            const ele = nodeList[i];
                            ele.nodeIndex = i;
                            handleOpterType(ele);
                        }

                        let procInstStatusArr = nodeList.filter(
                            item => item.procInstStatus === "INPROCESS",
                        );
                        activeNode = procInstStatusArr[procInstStatusArr.length - 1]?.nodeIndex;
                        set_stepInfo({
                            activeNode,
                            nodeList,
                        });
                    });
                }
            })
            .then(_ => {});
    };

    const getHistoryWorkflow = () => {
        findHistoryProcess(lastParams.kid).then(res => {
            if (res.success) {
                let historyData = [],
                    nodeList = [];
                for (let i = 0; i < res.data.length; i++) {
                    const ele = res.data[i];
                    for (let j = 0; j < ele.nodeList.length; j++) {
                        const ele2 = ele.nodeList[j];
                        ele2.procInstStatus = ele.procInstStatus;
                    }
                }
                res.data
                    .map(e => e.nodeList)
                    .reverse()
                    .forEach((val, idx) => {
                        val.sort().forEach(ee => {
                            historyData.push(ee);
                        });
                    });

                for (let z = 0; z < historyData.length; z++) {
                    const ele11 = historyData[z];
                    if (ele11.assigneeList) {
                        for (let d = 0; d < ele11.assigneeList.length; d++) {
                            const ele22 = ele11.assigneeList[d];
                            ele22.fileData = [];
                            if (ele22.taskId && showSignFile) {
                                // getUploadData(ele22.taskId).then(result => {
                                //     ele22.fileData = result;
                                // });
                            }
                        }
                    }
                }
                if (historyData.length > 0) {
                    nodeList = [
                        { nodeIndex: 0, nodeId: "0", nodeName: "流程开始", assigneeList: [] },
                    ];
                }
                nodeList = nodeList.concat(historyData);
                if (historyData.length > 0) {
                    // 退回，撤回，已完成都要显示流程结束
                    nodeList.push({
                        nodeId: "100",
                        nodeIndex: 100,
                        nodeName: "流程结束",
                        assigneeList: [],
                    });
                }
                for (let g = 0; g < nodeList.length; g++) {
                    const ele98 = nodeList[g];
                    handleOpterType(ele98);
                }
                set_stepInfo(stepInfo => {
                    return {
                        ...stepInfo,
                        nodeList,
                    };
                });
            }
        });
    };

    const getTitle = item => {
        let title = item.nodeName;
        if (item && item.assigneeList && item.assigneeList.length > 0) {
            title += "（" + item.assigneeList.map(ee => ee.userName).join(",") + "）";
        }
        return title;
    };

    // 处理展示操作展示类型
    const handleOpterType = item => {
        let fields = [];
        let currentOpter = item && item.procInstStatus ? item.procInstStatus : null;
        if (!item && !item.assigneeList) {
            return false;
        }
        for (let i = 0; i < item.assigneeList.length; i++) {
            const ele = item.assigneeList[i];
            if (currentOpter === "COMPLETE") {
                // 或签完成，其他未操作的人
                if (ele.operateType == null) {
                    ele.operateType = "NULL";
                } else {
                    ele.operateType = ele.operateType;
                }
            }
            if (currentOpter === "CANCEL") {
                // 撤销，未操作的人
                if (ele.operateType == null) {
                    ele.operateType = "CANCEL";
                }
            }
            if (currentOpter === "REJECT") {
                // 拒绝，未操作的人
                if (ele.operateType == null) {
                    ele.operateType = "NULL";
                } else {
                    ele.operateType = ele.operateType;
                }
            }
            if (currentOpter === "INPROCESS") {
                // 进行中，未操作的人
                if (ele.operateType == null) {
                    ele.operateType = "NULL";
                } else {
                    ele.operateType = ele.operateType;
                }
            }
            if (currentOpter === "NOTDONE") {
                // 预判节点，流程未进行
                fields.push({
                    userName: ele.userName,
                    endTime: null,
                    operateType: "NOTDONE",
                    reason: null,
                });
            } else {
                fields.push({
                    userName: ele.userName,
                    endTime: ele.endTime,
                    operateType: ele.operateType,
                    reason: ele.reason,
                    fileData: ele.fileData ? ele.fileData : [],
                });
            }
        }
    };

    useEffect(() => {
        if (lastParams.stateId < 1 || lastParams.stateId == 100) {
            getHistoryWorkflow();
        } else {
            getWorkflowKid();
        }
    }, []);

    const current = _stepInfo.activeNode || 1;

    return (
        <div className="flow-page">
            <NavBar back="返回" onBack={() => history.go(-1)}>
                <span>流转通知</span>
            </NavBar>
            {!_stepInfo.nodeList?.length ? (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            ) : (
                <div className="flow-container">
                    <Steps current={current} direction="vertical">
                        {_stepInfo.nodeList.map((node, idx) => {
                            const description = (
                                <Space block direction="vertical">
                                    {node.assigneeList.map((itm, i) => {
                                        return (
                                            <ul className="step-record" key={i}>
                                                <li className="reali">
                                                    {(node.nodeIndex !== 0 ||
                                                        node.nodeIndex != 100) && (
                                                        <div>
                                                            <div className="titles">
                                                                <div className="name">
                                                                    {itm.userName}
                                                                </div>
                                                                <div className="tis">
                                                                    <i
                                                                        style={{
                                                                            background:
                                                                                colors[
                                                                                    itm.operateType
                                                                                ],
                                                                        }}
                                                                        className="circle"
                                                                    ></i>
                                                                    {status[itm.operateType]}
                                                                </div>
                                                                {itm.endTime && (
                                                                    <div className="time">
                                                                        （{itm.endTime}）
                                                                    </div>
                                                                )}
                                                            </div>
                                                            <div className="reason">
                                                                意见： {itm.reason}
                                                            </div>
                                                            <ul className="files">
                                                                {itm.fileData.map((file, d) => {
                                                                    return (
                                                                        <li
                                                                            key={d}
                                                                            className="files-li"
                                                                        >
                                                                            {file.title}
                                                                        </li>
                                                                    );
                                                                })}
                                                            </ul>
                                                        </div>
                                                    )}
                                                </li>
                                            </ul>
                                        );
                                    })}
                                </Space>
                            );

                            return (
                                <Step
                                    key={idx}
                                    title={getTitle(node)}
                                    description={description}
                                    icon={<div className="step-icon">{idx + 1}</div>}
                                />
                            );
                        })}
                    </Steps>
                </div>
            )}
        </div>
    );
};

StatusFlow.propTypes = {
    store: storeShape,
    history: historyShape,
    location: locationShape,
};

export default StatusFlow;
